package com.delivery.deliverysystem.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.delivery.deliverysystem.common.ResponseCode;
import com.delivery.deliverysystem.dao.UserMapper;
import com.delivery.deliverysystem.exception.RException;
import com.delivery.deliverysystem.pojo.DO.DefaultName;
import com.delivery.deliverysystem.pojo.DO.User;
import com.delivery.deliverysystem.service.DefaultNameService;
import com.delivery.deliverysystem.dao.DefaultNameMapper;
import com.delivery.deliverysystem.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【default_name(默认字段以及是否显示表)】的数据库操作Service实现
* @createDate 2025-01-13 15:37:40
*/
@Service
@Slf4j
public class DefaultNameServiceImpl extends ServiceImpl<DefaultNameMapper, DefaultName>
    implements DefaultNameService{

    @Autowired
    private DefaultNameMapper defaultNameMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean updateDefaultName(Map<String, Object> defaultName) throws Exception {
        if(defaultName==null||defaultName.isEmpty()) return false;
        String username = JWTUtil.getCurrentUserCode();
        List<DefaultName> defaultNames = defaultNameMapper.selectList(null);
        if(defaultNames==null||defaultNames.isEmpty()) return false;
        Map<String,Object> map = new HashMap<>();
        for(DefaultName name:defaultNames){
            //遍历默认字段表，如果前端传来的map中包含该字段，则更新该字段的值，否则将该字段的值为默认值
            String originalName = name.getDefaultName();
            Object updateName = defaultName.get(originalName);
            if(updateName==null|| Objects.equals(updateName,"")|| Objects.equals(updateName," "))
                map.put(originalName, originalName);
            else map.put(originalName, updateName);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_code",username);
        User user = userMapper.selectOne(queryWrapper);
        //map->json
        String jsonString = JSONObject.toJSONString(map);
        user.setUpdateColumn(jsonString);
        return userMapper.updateById(user)>0;
    }


}




